package brad.zimmerman.dungeon.game;

import java.io.*;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.widget.ArrayAdapter;


public class ClassDatabaseAct extends SQLiteOpenHelper{

	private static final String DATABASE_NAME = "DungeonDatabase";
	
	private static final int DATABASE_VERSION = 37;
    private static final String DICTIONARY_TABLE_NAME = "HighScores";
    private static final String DICTIONARY_TABLE_CREATE =
                "CREATE TABLE " + DICTIONARY_TABLE_NAME + " ( _id Integer PRIMARY KEY, Race Integer, " +
                		"Class Integer, Lvl Integer, Rank Integer, Score Integer, Steps Integer," +
                		"Completed Integer);";
    
    private static final String TECH_TABLE_NAME = "Technology";
    private static final String TECH_TABLE_CREATE =
                "CREATE TABLE " + TECH_TABLE_NAME + " ( _id Integer PRIMARY KEY, Shield Integer, " +
                		"Armor Integer, Helm Integer, Boots Integer, Gloves Integer, Staff Integer," +
                		"Sword Integer, Mace Integer, Dice Integer, Scope Integer, Mining Integer," +
                		"Refining Integer, Medicine Integer, Barter Integer, Cities Integer, Religion Integer," +
                		"Knowledge Integer, Ritual Integer, mPotion Integer, hPotion Integer, Gold Integer);";
    
    private static final String GAME_TABLE_NAME = "GameTable";
    private static final String GAME_TABLE_CREATE =
            "CREATE TABLE " + GAME_TABLE_NAME + " (Race Integer, " +
            		"Class Integer, Lvl Integer, Rank Integer, Score Integer, Steps Integer, Completed Integer);";
    
    /*private static final String SETTINGS_TABLE_NAME = "SettingsTable";
    private static final String SETTINGS_TABLE_CREATE =
            "CREATE TABLE " + SETTINGS_TABLE_NAME + " ( _id Integer PRIMARY KEY, SfxVolume Integer, " +
            		"BackVolume Integer, Tiles Integer, Difficulty Integer);";*/

ClassDatabaseAct(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
	db.execSQL(TECH_TABLE_CREATE);
    db.execSQL(DICTIONARY_TABLE_CREATE);
    db.execSQL(GAME_TABLE_CREATE);
   // db.execSQL(SETTINGS_TABLE_CREATE);
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	  // TODO Auto-generated method stub
	  
	  db.execSQL("DROP TABLE IF EXISTS "+DICTIONARY_TABLE_NAME);
	  db.execSQL("DROP TABLE IF EXISTS "+TECH_TABLE_NAME);
	  db.execSQL("DROP TABLE IF EXISTS "+GAME_TABLE_NAME);
	 // db.execSQL("DROP TABLE IF EXISTS "+SETTINGS_TABLE_NAME);
	  onCreate(db);
	//  db=this.getWritableDatabase();
	 // db.execSQL("INSERT INTO "
	//	         + SETTINGS_TABLE_NAME
	//	         + " ( _id, SfxVolume,BackVolume, Tiles, Difficulty)"
	//	         + " VALUES (0, 100, 60, 20, 100);");
	//  db.close();
}

public void checkCreate(){
	if (!returnUsed(1, TECH_TABLE_NAME)){
		SQLiteDatabase db;
		db=this.getWritableDatabase();
		
		db.execSQL("INSERT INTO "
		         + TECH_TABLE_NAME
		         + " ( _id, Shield, " +
	             		"Armor, Helm, Boots, Gloves, Staff," +
	             		"Sword, Mace, Dice, Scope, Mining," +
	             		"Refining, Medicine, Barter, Cities, Religion," +
	             		"Knowledge, Ritual, mPotion, hPotion, Gold)"
		         + " VALUES (1, 0, " +
	             		"0, 0, 0, 0, 0," +
	             		"0, 0, 0, 0, 0," +
	             		"0, 0, 0, 0, 0," +
	             		"0, 0, 0, 0, 0);");
		db.close();
	}
}

public void InsertTech(String column, int value){
	SQLiteDatabase db;
	 if (!returnUsed(1, TECH_TABLE_NAME)){
			db=this.getWritableDatabase();
		 	db.execSQL("INSERT INTO "
	         + TECH_TABLE_NAME
	         + " ( _id, Shield, " +
             		"Armor, Helm, Boots, Gloves, Staff," +
             		"Sword, Mace, Dice, Scope, Mining," +
             		"Refining, Medicine, Barter, Cities, Religion," +
             		"Knowledge, Ritual, mPotion, hPotion, Gold)"
	         + " VALUES (1, 0, " +
             		"0, 0, 0, 0, 0," +
             		"0, 0, 0, 0, 0," +
             		"0, 0, 0, 0, 0," +
             		"0, 0, 0, 0, 0);");
		 	db.execSQL("UPDATE "
			         + TECH_TABLE_NAME
			         + " SET " + column + " = " + value + " WHERE _id = 1;");
		 	db.close();
	 }
	 else{
		 db=this.getWritableDatabase();
		 db.execSQL("UPDATE "
		         + TECH_TABLE_NAME
		         + " SET " + column + " = " + value + " WHERE _id = 1;");
	 	db.close();
	 }
}

public int returnTechValues(String column){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT "+column+" from "+TECH_TABLE_NAME +" WHERE _id = 1;",new String [] {});
	count = c.getCount();
	db.close();
	
	if (count> 0){
		c.moveToFirst();
		return c.getInt(0);
	}
	else{
		return -1;
	}
}
//This is to hold the data between activities. Less efficient, but gets around the memory leak problem without me having to put too much time into it
public void insertTempDatabase(int racetxt, int classtxt, int lvltxt, int ranktxt, int scoretxt, int stepstxt, int completed)
{
	SQLiteDatabase db;
	db=this.getWritableDatabase();
 	db.execSQL("INSERT INTO "
     + GAME_TABLE_NAME
     + " (Race, Class, Lvl, Rank, Score, Steps, Completed)"
     + " VALUES ("+ racetxt  + "," + classtxt + "," + lvltxt + "," + ranktxt + "," + scoretxt + 
     "," + stepstxt + "," + completed + ");");
 	db.close();
}
//This returns the values in the temporary database, and then clears the database
public int[] getTempDatabaseValues(){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from " + GAME_TABLE_NAME + ";",new String [] {});
	count = c.getCount();
	//Deletes all data from the table
	db.execSQL("DELETE FROM " +GAME_TABLE_NAME +";");
	db.close();
	//db.delete(GAME_TABLE_NAME,null,null);
	
	if (count> 0){
		c.moveToFirst();
		int[] values = {c.getInt(0),c.getInt(1),c.getInt(2),c.getInt(3),c.getInt(4),c.getInt(5),c.getInt(6)};
		return values;
	}
	else{
		return null;
	}
}

public boolean levelPlayed(){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from " + GAME_TABLE_NAME + ";",new String [] {});
	count = c.getCount();
	if (count>0){
		return true;
	}
	return false;
}

public void InsertDatabase(int primarykey, int racetxt, int classtxt, int lvltxt, int ranktxt, int scoretxt, int stepstxt, int completed)
{
//System.out.println(primarykey + " " + racetxt + " " + classtxt + " " + lvltxt + " " + ranktxt + " " + scoretxt + " " + stepstxt + " " + completed);
SQLiteDatabase db;
 if (!returnUsed(primarykey, DICTIONARY_TABLE_NAME)){
	 db=this.getWritableDatabase();
	 	db.execSQL("INSERT INTO "
         + DICTIONARY_TABLE_NAME
         + " (_id, Race, Class, Lvl, Rank, Score, Steps, Completed)"
         + " VALUES ( "+ primarykey + "," + racetxt  + "," + classtxt + "," + lvltxt + "," + ranktxt + "," + scoretxt + 
         "," + stepstxt + "," + completed + ");");
	 	db.close();
 }else{
	 db=this.getWritableDatabase();
	 db.execSQL("UPDATE "
	         + DICTIONARY_TABLE_NAME
	         + " SET Race = " + racetxt + ", Class = " + classtxt + ", Lvl = " + lvltxt + ", Rank = " + ranktxt +", Score = " + scoretxt + ", Steps = " + stepstxt + 
	         ", Completed = " + completed + " "
	         + " WHERE _id = "+ primarykey + ";");
	 db.close();
 }
 
}

public boolean returnUsed(int position, String Dictionary){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from "+ Dictionary +" WHERE _id = " + position + ";",new String [] {});
	count = c.getCount();
	db.close();
	
	if (count> 0){
		return true;
	}
	else{
		return false;
	}
}

public String returnHighScores(int prace, int pclass, int plvl, ClassDatabaseAct database, ClassDrawingHolder Draws){
	String HighScoreText = "";
    int[] highScoreValues = database.returnValues(DICTIONARY_TABLE_NAME,prace, pclass, plvl);
    //System.out.println(highScoreValues);
    if (highScoreValues != null){
    	HighScoreText += "Current High Score: " + highScoreValues[5] + "\n";
    	HighScoreText += "Greatest Level: " + highScoreValues[4] + "\n";
      if (highScoreValues[7] == 1)
    	  
    	{
    	  HighScoreText += "Completed: True	";
    	  HighScoreText += "# Steps: " + highScoreValues[6]; }
      else
      	{HighScoreText += "Completed: False";}
    }
    return HighScoreText;
}

public boolean returnCompleted(int prace, int pclass, int plvl, ClassDatabaseAct database, ClassDrawingHolder Draws){
    int[] highScoreValues = database.returnValues(DICTIONARY_TABLE_NAME,prace, pclass, plvl);
    if (highScoreValues != null){

      if (highScoreValues[7] == 1){
    	  return true;
    	  }else{
    	return false;}
    }
    return false;
}

public boolean returnClassUsed(int pclass, ClassDatabaseAct database){
    int[] highScoreValues = database.quickClassScan(DICTIONARY_TABLE_NAME,pclass);
    if (highScoreValues != null){
    	//System.out.println("True");
    	return true;
    }
    //System.out.println("False");
    return false;
}

public boolean returnLevelUsed(int level, ClassDatabaseAct database){
	int[] highScoreValues = database.quickLevelScan(DICTIONARY_TABLE_NAME,level);
    if (highScoreValues != null){
    	//System.out.println("True");
    	return true;
    }
    //System.out.println("False");
    return false;
}

public int[] returnScoreValues(int prace, int pclass, int plvl){
	return this.returnValues(DICTIONARY_TABLE_NAME,prace, pclass, plvl);
}

public int[] returnValues(String database, int prace, int pclass, int plvl){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	int playerID;
	playerID = (pclass+1) * 100 + (plvl+1);
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from "+database +" WHERE _id = " + playerID + ";",new String [] {});
	count = c.getCount();
	db.close();
	
	if (count> 0){
		c.moveToFirst();
		int[] values = {c.getInt(0),c.getInt(1),c.getInt(2),c.getInt(3),c.getInt(4),c.getInt(5),c.getInt(6),c.getInt(7)};
		return values;
	}
	else{
		return null;
	}
}

public int[] quickLevelScan(String database, int level){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	String playerID;
	playerID = "%" + level;
	//System.out.println(playerID);
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from "+database +" WHERE cast(_id as vachar(255)) like '" + playerID + "';",new String [] {});
	count = c.getCount();
	db.close();
	
	if (count> 0){
		c.moveToFirst();
		int[] values = {c.getInt(0),c.getInt(1),c.getInt(2),c.getInt(3),c.getInt(4),c.getInt(5),c.getInt(6),c.getInt(7)};
		return values;
	}
	else{
		return null;
	}
}

public int[] quickClassScan(String database, int pclass){
	int count;
	SQLiteDatabase db=this.getReadableDatabase();
	String playerID;
	playerID = (pclass+1) + "__";
	//System.out.println(playerID);
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from "+database +" WHERE cast(_id as vachar(255)) like '" + playerID + "';",new String [] {});
	count = c.getCount();
	db.close();
	
	if (count> 0){
		c.moveToFirst();
		int[] values = {c.getInt(0),c.getInt(1),c.getInt(2),c.getInt(3),c.getInt(4),c.getInt(5),c.getInt(6),c.getInt(7)};
		return values;
	}
	else{
		return null;
	}
}

public void printDatabase(){
	
	SQLiteDatabase db = this.getReadableDatabase();
	SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT * from "+DICTIONARY_TABLE_NAME +";",new String [] {});
    
     /* Check if our result was valid. */
	if (c.getCount()> 0){
		c.moveToFirst();
    for(int i = 0; i < c.getCount(); i++){
    	if (i!=0){
    		c.moveToNext();
    	}
    	 System.out.println("KEY: "+c.getInt(0) +" Values: "+ c.getString(1) + c.getString(2) + c.getString(3) + c.getString(4) + c.getInt(5) + c.getInt(6) + c.getInt(7));
     }
	}
     db.close();
}
}